﻿using Core.AdminUI.V2.Controllers.Base;
using Core.AdminUI.V2.Models;
using Core.FrameWork.Commons.ApiResult;
using Core.FrameWork.Commons.Encrypt;
using Core.FrameWork.Commons.Loging;
using Core.FrameWork.Commons.Mapping;
using Core.FrameWork.Models;
using Core.FrameWork.Models.Models.System;
using Masuit.Tools;
using Masuit.Tools.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Core.AdminUI.V2.Controllers
{
    /// <summary>
    /// 管理员页面
    /// </summary>
    public class UserManageController : BaseController
    {
        public UserManageController(AdminContext adminContext) : base(adminContext)
        {
        }
        #region 页面
        /// <summary>
        /// 列表页
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 添加页
        /// </summary>
        /// <returns></returns>
        public IActionResult Add()
        {
            var roleList = _adminContext.SysAspNetRoles.ToList();
            ViewBag.roleList = roleList;
            return View();
        }
        /// <summary>
        /// 修改页
        /// </summary>
        /// <returns></returns>
        public IActionResult Update(string userId = "")
        {
            if (!Guid.TryParse(userId, out var userGId))
            {
                return Redirect("Index");
            }

            var userInfo = _adminContext.SysAspNetUsers.Find(userGId);
            if (userInfo == null)
            {
                return Redirect("Index");
            }
            var roleIds = _adminContext.SysAspNetUserRoles.Where(x => x.SysAspNetUsersId == userGId).Select(s => s.RoleId).ToArray();
            var role = _adminContext.SysAspNetRoles.Where(s => roleIds.Contains(s.Id)).ToList();

            RespAdminUser admin = userInfo.MapTo<SysAspNetUsers, RespAdminUser>();
            admin.Roles = string.Join(',', role.Select(s => s.Name));
            admin.RoleIds = role.Select(s => s.Id).ToList();


            var roleList = _adminContext.SysAspNetRoles.ToList();
            ViewBag.roleList = roleList;

            return View(admin);
        }
        /// <summary>
        /// 重置密码页
        /// </summary>
        /// <returns></returns>
        public IActionResult UpdPwd(string userId = "")
        {
            if (!Guid.TryParse(userId, out var userGId))
            {
                return Redirect("Index");
            }

            var userInfo = _adminContext.SysAspNetUsers.Find(userGId);
            if (userInfo == null)
            {
                return Redirect("Index");
            }
            ViewBag.Id = userInfo.Id;

            return View();
        }
        #endregion

        #region 接口
        /// <summary>
        /// 获取管理员列表数据
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="name"></param>
        /// <param name="email"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionDescription("获取管理员列表数据", LogResponseData = false)]
        public PageResult<RespAdminUser> GetPageList(int page = 1, int limit = 10, string name = "", string email = "")
        {
            Expression<Func<SysAspNetUsers, bool>> exp = m => true;

            if (!string.IsNullOrEmpty(name))
            {
                exp = exp.And(s => s.TrueName.Contains(name));
            }

            if (!string.IsNullOrEmpty(email))
            {
                exp = exp.And(s => s.Email.Contains(email));
            }

            var list = _adminContext.SysAspNetUsers.Include(s => s.SysAspNetUserRoles).Where(exp).OrderByDescending(m => m.CreateTime)
            .Skip((page - 1) * limit)
            .Take(limit).Select(s => new RespAdminUser()
            {
                Email = s.Email,
                Phone = s.Phone,
                TrueName = s.TrueName,
                Id = s.Id,
                RoleIds = s.SysAspNetUserRoles.Select(s => s.RoleId).ToList(),
                CreateTime = s.CreateTime,
                Address = s.Address,
                Company = s.Company,
                Name = s.Name,
                Enabled = s.Enabled,
                LastModifyTime = s.LastModifyTime
            }).ToList()
            .ToList();

            int count = _adminContext.SysAspNetUsers.Count(exp);

            List<Guid> roleIds = new List<Guid>();

            list.ForEach(m =>
            {
                m.RoleIds.ForEach(s =>
                {
                    roleIds.Add(s);
                });
            });

            var UserRoles = _adminContext.SysAspNetRoles.Where(m => roleIds.Contains(m.Id)).ToList();


            foreach (var item in list)
            {
                //查询当前有什么角色
                //var roles = UserRoles.Where(m => m.Id == item.Id).GroupBy(m => m.Id).Select(m => m.Key).ToList();
                string roleNames = string.Join(',', UserRoles.Where(m => item.RoleIds.Contains(m.Id)).Select(m => m.Name).ToArray());
                item.Roles = roleNames;
            }
            return ApiRespHelp.getApiDataListByPage(list, count, page, limit);

        }
        /// <summary>
        /// 修改管理员信息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("修改管理员信息", LogResponseData = true)]
        public CommonResult Update([FromBody] ReqEditAdminUser req)
        {
            var userInfo = _adminContext.SysAspNetUsers.Find(req.Id);

            if (userInfo == null)
            {
                return ApiRespHelp.getError(-100, "指定管理员不存在");
            }

            //是否有相同的手机号
            var phCnt = _adminContext.SysAspNetUsers.Count(m => m.Phone == req.Phone && m.Phone != userInfo.Phone);
            if (phCnt > 0)
            {
                return ApiRespHelp.getError(-100, "手机号重复");
            }
            //是否有相同的邮箱
            var EmCnt = _adminContext.SysAspNetUsers.Count(m => m.Email == req.Email && m.Email != userInfo.Email);
            if (EmCnt > 0)
                return ApiRespHelp.getError(-100, "邮箱重复");

            userInfo.TrueName = req.TrueName;
            userInfo.Phone = req.Phone;
            userInfo.Email = req.Email;
            userInfo.Address = req.Address;
            userInfo.Company = req.Company;
            userInfo.LastModifyTime = DateTime.Now;
            userInfo.LastModifyUserId = Guid.Parse(CurrentUser.Id);
            userInfo.LastModifyUserName = CurrentUser.Name;

            //删除原来的角色
            var userroles = _adminContext.SysAspNetUserRoles.Where(m => m.SysAspNetUsersId == userInfo.Id).ToList();
            _adminContext.SysAspNetUserRoles.RemoveRange(userroles);
            //重新添加角色
            string[] roles = req.Roles.Trim(',').Split(",");
            foreach (var item in roles)
            {
                SysAspNetUserRoles role = new SysAspNetUserRoles()
                {
                    Id = Guid.NewGuid(),
                    RoleId = Guid.Parse(item),
                    SysAspNetUsersId = userInfo.Id
                };
                _adminContext.SysAspNetUserRoles.Add(role);
            }

            int num = _adminContext.SaveChanges();
            if (num > 0)
                return ApiRespHelp.getSuccess("编辑成功");
            return ApiRespHelp.getError(-100, "编辑失败");
        }
        /// <summary>
        /// 新增管理员
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("新增管理员", LogResponseData = true)]
        public CommonResult AddUser([FromBody] ReqAddAdminUser req)
        {
            var cnt = _adminContext.SysAspNetUsers.Count(m => m.Phone == req.Phone);
            if (cnt > 0)
                return ApiRespHelp.getError(-100, "手机号重复");
            cnt = _adminContext.SysAspNetUsers.Count(m => m.Email == req.Email);
            if (cnt > 0)
                return ApiRespHelp.getError(-100, "邮箱重复");

            req.Enabled = true;

            var model = req.MapTo<ReqAddAdminUser, SysAspNetUsers>();

            _adminContext.SysAspNetUsers.Add(model);
            //添加角色
            string[] roles = req.Roles.Trim(',').Split(",");
            foreach (var item in roles)
            {
                SysAspNetUserRoles role = new SysAspNetUserRoles()
                {
                    Id = Guid.NewGuid(),
                    RoleId = Guid.Parse(item),
                    SysAspNetUsersId = model.Id
                };
                _adminContext.SysAspNetUserRoles.Add(role);
            }

            int num = _adminContext.SaveChanges();
            if (num > 0)
                return ApiRespHelp.getSuccess("新增成功");
            return ApiRespHelp.getError(-100, "新增失败");
        }
        /// <summary>
        /// 删除管理员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("删除管理员", LogResponseData = true)]
        public CommonResult Delete(string Id)
        {
            if (!Guid.TryParse(Id, out var GId))
            {
                return ApiRespHelp.getError(-100, "管理员Id 格式错误");
            }

            var userInfo = _adminContext.SysAspNetUsers.Find(GId);

            userInfo.IsDelete = 1;
            userInfo.DeleteUser = Guid.Parse(CurrentUser.Id);
            userInfo.DeleteUserName = CurrentUser.Name;
            userInfo.DeleteTime = DateTime.Now;

            if (_adminContext.SaveChanges() == 0)
            {
                return ApiRespHelp.getError(-100, "操作失败");
            }

            return ApiRespHelp.getSuccess("操作成功");
        }
        /// <summary>
        /// 批量删除管理员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("批量删除管理员", LogResponseData = true)]
        public CommonResult BatchDelete(string Ids)
        {
            if (string.IsNullOrEmpty(Ids))
            {
                return ApiRespHelp.getError(-100, "Id不能为空");
            }

            var listIds = Ids.Split(',').Select(s => Guid.Parse(s));

            var userInfo = _adminContext.SysAspNetUsers.Where(s => listIds.Contains(s.Id)).ToList();

            userInfo.ForEach(userInfo =>
            {
                userInfo.IsDelete = 1;
                userInfo.DeleteUser = Guid.Parse(CurrentUser.Id);
                userInfo.DeleteUserName = CurrentUser.Name;
                userInfo.DeleteTime = DateTime.Now;
            });

            if (_adminContext.SaveChanges() == 0)
            {
                return ApiRespHelp.getError(-100, "操作失败");
            }

            return ApiRespHelp.getSuccess("操作成功");
        }

        /// <summary>
        /// 修改管理员状态
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="isDelete"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("修改管理员状态", LogResponseData = true)]
        public CommonResult Enable(string Id)
        {
            if (!Guid.TryParse(Id, out var GId))
            {
                return ApiRespHelp.getError(-100, "管理员Id 格式错误");
            }

            var model = _adminContext.SysAspNetUsers.Find(GId);

            if (model.Enabled)
            {
                model.Enabled = false;
            }
            else
            {
                model.Enabled = true;
            }


            int num = _adminContext.SaveChanges();
            if (num > 0)
                return ApiRespHelp.getSuccess("操作成功");
            return ApiRespHelp.getError(-100, "error");
        }
        /// <summary>
        /// 重置管理员密码
        /// </summary>
        /// <param name="oldpwd"></param>
        /// <param name="newpwd"></param>
        /// <param name="newpwd1"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("重置管理员密码", LogResponseData = true)]
        public CommonResult UpdPwd(string Id, string newpwd, string newpwd1)
        {
            if (!Guid.TryParse(Id, out var GId))
            {
                return ApiRespHelp.getError(-100, "管理员Id不能为空");
            }
            if (string.IsNullOrEmpty(newpwd))
            {
                return ApiRespHelp.getError(-100, "密码不能为空");
            }
            if (string.IsNullOrEmpty(newpwd1))
            {
                return ApiRespHelp.getError(-100, "确认密码不能为空");
            }

            if (newpwd.Length < 6 || newpwd1.Length < 6)
            {
                return ApiRespHelp.getError(-100, "密码不得小于6个字符");
            }
            if (newpwd != newpwd1)
            {
                return ApiRespHelp.getError(-100, "新密码不一致");
            }
            var user = _adminContext.SysAspNetUsers.Find(GId);
            if (user.Password == MD5Util.GetMD5_16(newpwd))
            {
                return ApiRespHelp.getError(-100, "新密码不能与原密码一致");
            }
            user.Password = MD5Util.GetMD5_16(newpwd);
            user.LastModifyTime = DateTime.Now;
            int num = _adminContext.SaveChanges();
            if (num > 0)
                return ApiRespHelp.getSuccess("修改成功");
            return ApiRespHelp.getError(-100, "修改失败");

        }
        #endregion

    }
}
